<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="用户名" prop="username">
        <el-select v-model="userList.id" placeholder="请选择当前状态" clearable>
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.username"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="当前状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择当前状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.cr_approve_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否出租" prop="isRent">
        <el-select
          v-model="queryParams.isRent"
          placeholder="请选择是否出租"
          clearable
        >
          <el-option
            v-for="dict in dict.type.cr_rend"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="空闲时间" prop="rentalPeriod">
        <el-date-picker
          v-model="queryParams.rentalPeriod"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manager:car:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manager:car:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manager:car:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manager:car:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="carList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车辆ID" align="center" prop="id"/>
      <el-table-column label="用户" align="center" prop="username"/>
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="座位数" align="center" prop="seatingCapacity"/>
      <el-table-column label="价格" align="center" prop="price"/>
      <el-table-column label="颜色" align="center" prop="color"/>
      <el-table-column label="年份" align="center" prop="year"/>
      <el-table-column label="图片" align="center" prop="image">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="详情" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="browseDetail(scope.row.detail)" v-hasPermi="['manager:car:browse']">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="空闲时间" align="center" width="180px">
        <template slot-scope="scope">
          {{ scope.row.rentalStart }} - {{ scope.row.rentalEnd }}
        </template>
      </el-table-column>
      <el-table-column
        label="当前状态"
        align="center"
        prop="status"
        width="150"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.cr_approve_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="是否出租"
        align="center"
        prop="isRent"
        width="150"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cr_rend" :value="scope.row.isRent" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width" width="120px"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleAudit(scope.row)"
            v-hasPermi="['manager:car:audit']"
            v-if="scope.row.status == 1"
            >审核</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manager:car:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manager:car:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 判断审核是否通过 -->
    <el-dialog :visible.sync="audit" title="是否审核通过" width="30%" center>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleConfirm">确认</el-button>
          <el-button type="primary" @click="handleCancel">拒绝</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情 -->
    <el-dialog :visible.sync="detail" title="车辆详情" width="30%" center>
      {{ detailText }}
    </el-dialog>

    <!-- 添加或修改车辆管理对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1100px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="userId">
              <el-select v-model="form.userId" placeholder="请选择用户名">
                <el-option
                  v-for="dict in userList"
                  :key="dict.id"
                  :label="dict.username"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择当前状态">
                <el-option
                  v-for="dict in dict.type.cr_approve_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="空闲时间开始" prop="rentalStart">
              <el-date-picker
                v-model="form.rentalStart"
                type="datetime"
                placeholder="选择日期时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                @change="rentalStartChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="空闲时间结束" prop="rentalEnd">
              <el-date-picker
                v-model="form.rentalEnd"
                type="datetime"
                placeholder="选择日期时间"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片" prop="image">
          <image-upload v-model="form.image" @successUpload="successUpload" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-input v-model="form.color" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="座位数" prop="seatingCapacity">
              <el-input v-model="form.seatingCapacity" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input v-model="form.price" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年份" prop="year">
              <el-input v-model="form.year" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详情" prop="detail">
              <el-input v-model="form.detail" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCar, getCar, delCar, addCar, updateCar } from "@/api/manager/car";
import { listUser } from "@/api/manager/user";

export default {
  name: "Car",
  dicts: ["cr_approve_status", "cr_rend"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆管理表格数据
      carList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否审核通过弹出框
      audit: false,
      // 查看详情
      detail: false,
      detailText: "",
      // 进行审核的carId
      auditId: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        brand: null,
        color: null,
        price: null,
        seatingCapacity: null,
        year: null,
        detail: null,
        rentalStart: null,
        rentalEnd: null,
        rentalPeriod: null,
        status: null,
        isRent: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        rentalEnd: [
          { required: true, message: "空闲时间开始不能为空", trigger: "blur" },
        ],
        rentalStart: [
          { required: true, message: "空闲时间结束不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "当前状态不能为空", trigger: "blur" },
        ],
        isRent: [
          { required: true, message: "是否出租不能为空", trigger: "blur" },
        ],
        image: [{ required: true, message: "图片不能为空", trigger: "blur" }],
      },
      userList: [],
      pickerOptions: {
        // 限制日期
        disabledDate: this.disabledDate,
      },
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询车辆管理列表 */
    getList() {
      this.loading = true;
      if (this.queryParams && this.queryParams.rentalPeriod) {
        let dateStart = new Date(this.queryParams.rentalPeriod[0]);
        let yearStart = dateStart.getFullYear();
        let monthStart = String(dateStart.getMonth() + 1).padStart(2, "0");
        let dayStart = String(dateStart.getDate()).padStart(2, "0");
        let dateEnd = new Date(this.queryParams.rentalPeriod[1]);
        let yearEnd = dateEnd.getFullYear();
        let monthEnd = String(dateEnd.getMonth() + 1).padStart(2, "0");
        let dayEnd = String(dateEnd.getDate()).padStart(2, "0");
        this.queryParams.rentalStart = `${yearStart}-${monthStart}-${dayStart}`;
        this.queryParams.rentalEnd = `${yearEnd}-${monthEnd}-${dayEnd}`;
      }
      listCar(this.queryParams).then((response) => {
        this.carList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取用户列表
    getUserList() {
      listUser().then((response) => {
        this.userList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryParams");
      this.queryParams = {
        userId: null,
        brand: null,
        color: null,
        price: null,
        seatingCapacity: null,
        year: null,
        detail: null,
        rentalStart: null,
        rentalEnd: null,
        rentalPeriod: null,
        status: null,
        isRent: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车辆管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCar(id).then((response) => {
        this.form = response.data;
        console.log(response.data);
        this.open = true;
        this.title = "修改车辆管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCar(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCar(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除车辆管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCar(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "manager/car/export",
        {
          ...this.queryParams,
        },
        `car_${new Date().getTime()}.xlsx`
      );
    },
    // 图片上传成功
    successUpload(carList) {
      console.log(carList);
      // 补充车辆信息，包括品牌、颜色
      this.form.brand = carList[0].brand;
      this.form.color = carList[0].color;
      this.form.seatingCapacity = carList[0].seatingCapacity;
      this.form.year = carList[0].year;
      this.form.detail = carList[0].detail;
      this.form.price = carList[0].price;
    },
    // 禁止选择空闲时间开始及之前的日期
    disabledDate(time) {
      if (this.form.rentalStart) {
        // 设置空闲时间范围为两个月
        return (
          time.getTime() < new Date(this.form.rentalStart) ||
          time.getTime() >
            new Date(
              new Date(this.form.rentalStart).getTime() +
                60 * 24 * 60 * 60 * 1000
            )
        );
      }
    },
    // 监听空闲时间开始时间变化
    rentalStartChange() {
      if (
        this.form.rentalEnd &&
        (this.form.rentalEnd <= this.form.rentalStart ||
          this.form.rentalEnd.getTime() >
            new Date(
              new Date(this.form.rentalStart).getTime() +
                7 * 24 * 60 * 60 * 1000
            ).getTime())
      ) {
        this.form.rentalEnd = new Date(
          new Date(this.form.rentalStart).getTime() + 24 * 60 * 60 * 1000
        );
      }
    },
    // 打开审核弹出框
    handleAudit(row) {
      this.reset();
      this.audit = true;
      this.auditId = row.id;
    },
    // 确认审核通过
    handleConfirm() {
      console.log("通过：" + this.auditId);
      this.audit = false;
      updateCar({ id: this.auditId, status: 2 }).then((response) => {
        this.$modal.msgSuccess("审核通过");
        this.getList();
      });
    },
    // 拒绝审核通过
    handleCancel() {
      console.log("拒绝：" + this.auditId);
      this.audit = false;
      updateCar({ id: this.auditId, status: 3 }).then((response) => {
        this.$modal.msgSuccess("审核拒绝");
        this.getList();
      });
    },
    // 查看详情
    browseDetail(detail){
      this.detail = true;
      this.detailText = detail;
    }
  },
};
</script>
